﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Admin_frmProductsAddModify : System.Web.UI.Page
{
    clsUser clsUser;
    clsProductsRecord clsProductsRecord;

    #region EVENT METHODS

    protected void Page_Load(object sender, EventArgs e)
    {
        //### Check if session clsUser exists
        if (Session["clsUser"] == null)
        {
            {
                //### Redirect back to login
                Response.Redirect("../frmAdminLogin.aspx");
            }
        }

        clsUser = (clsUser)Session["clsUser"];

        //### Determins if a javascript delete has been called
        if (!String.IsNullOrEmpty(Page.Request["__EVENTARGUMENT"]) && (Page.Request["__EVENTARGUMENT"].Split(':')[0] == "iRemoveImg"))
            DeleteImage(Convert.ToInt32(Page.Request["__EVENTARGUMENT"].Split(':')[1]));

        if (!IsPostBack)
        {
            POPLst();
            //### If the iProductID is passed through then we want to instantiate the obect with that iProductID
            if (Request.QueryString["iProductID"] != "" && Request.QueryString["iProductID"] != null)
            {
                //## Set label to modify
                lblAddModify.Text = "Modify Product";

                clsProductsRecord = new clsProductsRecord(clsUser, Convert.ToInt32(Request.QueryString["iProductID"]));

                //### Populate the form
                popFormData();
            }
            else
            {
                //### Set label to add
                lblAddModify.Text = "Add Product";

                clsProductsRecord = new clsProductsRecord(clsUser);
            }
            Session["clsProductsRecord"] = clsProductsRecord;
        }
        else
        {
            clsProductsRecord = (clsProductsRecord)Session["clsProductsRecord"];
        }
    }

    protected void btnBack_Click(object sender, ImageClickEventArgs e)
    {
        //### Go back to previous page
        Response.Redirect("frmProductsView.aspx");
    }

    protected void btnSave_Click(object sender, ImageClickEventArgs e)
    {
        //### Validate registration process
        bool bCanSave = true;

        //bCanSave = clsValidation.IsNullOrEmpty(txtProductTitle, reqTitle, bCanSave);
        //bCanSave = clsValidation.IsNullOrEmpty(txtDubblePrice, reqDubblePrice, bCanSave);

        if (bCanSave == true)
        {
            SaveData();
        }
        else
        {
            reqContainerDiv.Visible = true;
        }
    }

    protected void btnClear_Click(object sender, ImageClickEventArgs e)
    {
        reqContainerDiv.Visible = false;

        //txtProductTitle.Text = "";
        //clsValidation.SetValid(txtProductTitle, reqTitle);

        //txtDubblePrice.Text = "";
        //clsValidation.SetValid(txtDubblePrice, reqDubblePrice);
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (Session["lstImages"] == null)
        {
            lstImages = new List<string>();
            Session["lstImages"] = lstImages;
        }

        //### Check that they have only 1 image in the datalist
        if (dlImages.Items.Count == iMaxImages)
        {
            reqContainerDiv.Visible = true;
            reqPathToImage.Attributes.Add("style", "display:block");
            lblUploadError.Text = "";
            lblImagesError.Text = "You can only have " + iMaxImages.ToString() + " image.";
            getList(lblUniquePath.Text);
        }
        else
        {
            reqContainerDiv.Visible = false;
            reqPathToImage.Attributes.Add("style", "display:none");

            string strUniquePath;
            if (lblUniquePath.Text == "")
            {
                strUniquePath = GetUniquePath();
                lblUniquePath.Text = strUniquePath;
            }
            else
            {
                strUniquePath = lblUniquePath.Text;
            }
            UploadImage(strUniquePath);
            getList(strUniquePath);
        }
    }

    #endregion

    #region POPULATE DATA METHODS

    private void POPLst()
    {
        clsProductCategoryList clsProductCategoryList = new clsProductCategoryList(clsUser);
        lstCategory.DataSource = clsProductCategoryList.GetRecords();
        lstCategory.DataMember = "iProductCategoryID";
        lstCategory.DataTextField = "strCategoryName";
        lstCategory.DataBind();
    }

    private void popFormData()
    {
        //txtProductTitle.Text = clsProductsRecord.strProductTitle;
        //txtShortDescription.Text = clsProductsRecord.strShortDescription;
        //txtFullDiscription.Text = clsProductsRecord.strFullDescription;
        //txtDubblePrice.Text = clsProductsRecord.dblPrice.ToString();

        //if (!string.IsNullOrEmpty(clsProductsRecord.strPathToImages))
        //{
        //    lblUniquePath.Text = clsProductsRecord.strPathToImages;
        //    getList(clsProductsRecord.strPathToImages);

        //    //### Set Current Master Image
        //    List<string> lstImageFileName = (List<string>)Session["lstImageFileNames"];

        //    foreach (string strImageFileName in lstImageFileName)
        //    {
        //        if (strImageFileName == clsProductsRecord.strMasterImage)
        //        {
        //            RadioButton rdbMasterImage = dlImages.Items[lstImageFileName.IndexOf(strImageFileName)].FindControl("rdbMainImage") as RadioButton;
        //            rdbMasterImage.Checked = true;
        //            break;
        //        }
        //    }
        //}
    }

    #endregion

    #region SAVE DATA METHODS

    private void SaveData()
    {

        //### Add / Update
        clsProductsRecord.dtAdded = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
        clsProductsRecord.iAddedBy = clsUser.iUserID;
        clsProductsRecord.dtEdited = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
        clsProductsRecord.iEditedBy = clsUser.iUserID;
        clsProductsRecord.strProductName = txtProductName.Text;
        clsProductsRecord.strProductShortDesc = txtShortDescription.Text;
        clsProductsRecord.strProductFullDesc = txtFullDescription.Text;
        clsProductsRecord.dblPrice = Convert.ToDouble(txtPrice.Text);
        clsProductsRecord.iProductCategory = Convert.ToInt16(lstCategory.SelectedValue);
        clsProductsRecord.iViewed = 0;
        clsProductsRecord.iInStock = Convert.ToInt16(txtProductsInStock.Text);
        //clsProductsRecord.strProductTitle = txtProductTitle.Text;
        //clsProductsRecord.strShortDescription = txtShortDescription.Text;
        //clsProductsRecord.strFullDescription = txtFullDiscription.Text;
        //clsProductsRecord.dblPrice = Convert.ToDouble(txtDubblePrice.Text);
        //clsProductsRecord.strPathToImages = lblUniquePath.Text;
        //clsProductsRecord.strMasterImage = GetMainImagePath(dlImages);
        clsProductsRecord.bIsActive = true;

        clsProductsRecord.Update();

        //### redirect back to view page
        Response.Redirect("frmProductsView.aspx");
    }

    #endregion

    #region GALLERY

    List<string> lstImages;
    List<string> lstImageFileNames;
    int iMaxImages = 5;

    string strUniqueFullPath = System.Configuration.ConfigurationManager.AppSettings["WebRootFullPath"] + "\\ProductImages";

    public void getList(String strPathToFolder)
    {
        lstImages = new List<string>();
        lstImageFileNames = new List<string>();

        try
        {
            string strPath = strPathToFolder;
            string[] files = Directory.GetFiles(strUniqueFullPath + "\\" + strPath);

            string iProductID = "";
            if (!string.IsNullOrEmpty(Request.QueryString["iProductID"]))
                iProductID = Request.QueryString["iProductID"];

            int iImageCount = 0;
            foreach (string str in files)
            {
                if (str.IndexOf("_sml") != -1)
                {

                    string strHTMLImage = str.Replace(System.Configuration.ConfigurationManager.AppSettings["WebRootFullPath"] + "\\", "..\\");
                    strHTMLImage = strHTMLImage.Replace("\\", "/");

                    //### Generates a javascript postback for the delete method
                    String strPostBack = Page.ClientScript.GetPostBackEventReference(this, "iRemoveImg:" + iImageCount);

                    lstImages.Add(@"<tr style='text-align: centre;'>
                                        <td style='text-align: centre;'>
                                            <img src='" + strHTMLImage + @"' alt='" + Path.GetFileNameWithoutExtension(str) + @"' title='" + Path.GetFileNameWithoutExtension(str) + @"' style='border: solid 5px #ffffff;' /><br /><br />" +
                                                              "<center><div class='buttonStyle' style='padding-top: 5px;'><a href=\"javascript:" + strPostBack + "\" style='color: #ffffff;'><img src='images/btnGalleryDeleteImage.png' alt='Delete Image' title='Delete Image Button' style='border: none;' /></a></div></center>" + @"
                                        </td>
                                    </tr>");
                    lstImageFileNames.Add(Path.GetFileName(str).Replace("_sml", ""));
                    iImageCount++;
                }
            }
            dlImages.DataSource = lstImages;
            dlImages.DataBind();

            Session["lstImages"] = lstImages;
            Session["lstImageFileNames"] = lstImageFileNames;
        }
        catch (Exception ex)
        { }
    }

    private string GetUniquePath()
    {
        int iCount;

        iCount = 1;

        //###First we need to get the path
        while (System.IO.Directory.Exists(strUniqueFullPath + "\\Product" + iCount) == true)
        {
            iCount++;
        }
        return "Product" + iCount;
    }

    protected void UploadImage(String strUniquePath)
    {
        if (FIleUpload.PostedFile.ContentLength > 0 && FIleUpload.PostedFile.ContentLength < 1073741824)
        {
            //### Upload files to unique folder
            string strUploadFileName = "";
            strUploadFileName = System.IO.Path.GetFileName(FIleUpload.PostedFile.FileName);

            string strSaveLocation = "";
            strSaveLocation = strUniqueFullPath + "\\" + strUniquePath + "\\" + strUploadFileName;

            if (!System.IO.Directory.Exists(strUploadFileName + "\\" + strUniquePath))
            {
                System.IO.Directory.CreateDirectory(strUniqueFullPath + "\\" + strUniquePath);
            }
            FIleUpload.PostedFile.SaveAs(strSaveLocation);

            CopyAndResizePic(strSaveLocation);
            getList(strUniqueFullPath + "\\" + strUniquePath);
        }
        else
        {
            lblImagesError.Text = "The file should be between 0 and 1Mb.";
            lblUploadError.Text = "The file should be between 0 and 1Mb.";
        }
    }

    private void CopyAndResizePic(String strFullPath)
    {
        try
        {
            String strFileName;
            String strNewFilePath;

            //### Main image
            String strLrgFileName;

            strFileName = Path.GetFileName(strFullPath);
            strNewFilePath = strFullPath.Replace(strFileName, "");
            strNewFilePath = strNewFilePath + Path.GetFileNameWithoutExtension(strFullPath);
            strNewFilePath = strNewFilePath + "_lrg";
            strNewFilePath = strNewFilePath + Path.GetExtension(strFullPath);

            File.Copy(strFullPath, strNewFilePath);
            strLrgFileName = Path.GetFileName(strNewFilePath);

            clsCommonFunctions.ResizeImage(strNewFilePath, strNewFilePath, 600, 600, false);

            //### Listing image
            String strMedFileName;

            strFileName = Path.GetFileName(strFullPath);
            strNewFilePath = strFullPath.Replace(strFileName, "");
            strNewFilePath = strNewFilePath + Path.GetFileNameWithoutExtension(strFullPath);
            strNewFilePath = strNewFilePath + "_med";
            strNewFilePath = strNewFilePath + Path.GetExtension(strFullPath);

            File.Copy(strFullPath, strNewFilePath);
            strMedFileName = Path.GetFileName(strNewFilePath);

            clsCommonFunctions.ResizeImage(strNewFilePath, strNewFilePath, 200, 200, false);

            //### Thumbnail
            String strSmlFileName;

            strFileName = Path.GetFileName(strFullPath);
            strNewFilePath = strFullPath.Replace(strFileName, "");
            strNewFilePath = strNewFilePath + Path.GetFileNameWithoutExtension(strFullPath);
            strNewFilePath = strNewFilePath + "_sml";
            strNewFilePath = strNewFilePath + Path.GetExtension(strFullPath);

            File.Copy(strFullPath, strNewFilePath);
            strSmlFileName = Path.GetFileName(strNewFilePath);

            clsCommonFunctions.ResizeImage(strNewFilePath, strNewFilePath, 142, 97, false);

        }
        catch (Exception ex)
        { }
    }

    private string GetMainImagePath(DataList dtlTarget)
    {
        string strReturn = "";

        foreach (DataListItem dliTarget in dtlTarget.Items)
        {
            RadioButton rdbMainImage = (RadioButton)dliTarget.FindControl("rdbMainImage");

            if (rdbMainImage.Checked)
            {
                lstImageFileNames = (List<string>)Session["lstImageFileNames"];
                strReturn = lstImageFileNames[dliTarget.ItemIndex];
                break;
            }
        }

        return strReturn;
    }

    private void DeleteImage(int iImageIndex)
    {
        lstImages = (List<string>)Session["lstImages"];
        lstImageFileNames = (List<string>)Session["lstImageFileNames"];

        lstImages.RemoveAt(iImageIndex);
        Session["lstImages"] = lstImages;

        string[] files = Directory.GetFiles(strUniqueFullPath + "\\" + lblUniquePath.Text);

        foreach (string file in files)
        {
            if (Path.GetFileName(file) == lstImageFileNames[iImageIndex].ToString())
            {
                //### Remove all images
                File.Delete(file);
                File.Delete(file.Replace(Path.GetExtension(file), "_sml" + Path.GetExtension(file)));
                File.Delete(file.Replace(Path.GetExtension(file), "_med" + Path.GetExtension(file)));
                File.Delete(file.Replace(Path.GetExtension(file), "_lrg" + Path.GetExtension(file)));
                break;
            }
        }

        lstImageFileNames.RemoveAt(iImageIndex);
        ViewState["lstImageFileNames"] = lstImageFileNames;

        getList(lblUniquePath.Text);
    }

    #endregion
}